"use strict"
const mvc = require('cosjs.mvc');
const random = mvc.library.require('random');
const time = mvc.library.require('time');

/**
 * @name weekBoss
 * 崩塌梦境boss
 */


/**
 * @name getData
 * @param string activeID 活动ID
 * 获取活动信息
 */
exports.getData = async function () {
    let activeID = this.get('activeID', 'string');
    let battleCache = this.model.redis("weekBossCache", this.sid);
    let battleTempData = await battleCache.get(this.uid) || {};
    if (battleTempData.stageData) {
        battleTempData.stageData = JSON.parse(battleTempData.stageData);
    }
    if (battleTempData.maxWordLevel) {
        battleTempData.maxWordLevel = JSON.parse(battleTempData.maxWordLevel);
    }
    if (battleTempData.score) {
        battleTempData.score = JSON.parse(battleTempData.score);
    }
    if (battleTempData.time) {
        battleTempData.time = JSON.parse(battleTempData.time);
    }
    return battleTempData;
}


/**
 * @name startBattle
 * @param string activeID 活动ID
 * @param int stageID 关卡ID
 * 开始战斗
 */
exports.startBattle = async function () {
    let activeID = this.get('activeID', 'string');
    let stageID = this.get('stageID', 'int');
    //判断活动是否存在且在开启时间
    let query = {
    };
    query = {
        "_id": activeID,

    };
    let api = '/active/getAllByType',
        data = {
            "query": query,
            "keys": ["item", "s_key", "s_skin", "AType", "content", "name", "simg"],
        };
    return this.library('spirit/gzone', api, data).then(async ret => {
        if (!ret) {
            return;
        }
        let data = ret[0];
        if (data.s_key != 10001) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        let activeBeginTime = time.today(ret[0].STime);
        let todayBeginTime = time.today(this.updater.time);
        let circleDay = 7;
        //判断今天距离开启活动时间过去了多少天
        let subday = (todayBeginTime - activeBeginTime) / (24 * 60 * 60 * 1000) % circleDay;
        console.log("距离活动开启已经过去:" + subday + "天")
        if (!data.s_skin) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        let m = data.s_skin;
        let stageCompleteID = m * 1000 + subday + 1;
        //判断关卡ID是否匹配
        if (stageID != stageCompleteID) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        let stageConfig = this.config("actStage", stageID);
        if (!stageConfig) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        let battleCache = this.model.redis("weekBossCache", this.sid);
        //获取今日数据
        let battleTempData = await battleCache.get(this.uid);
        if (!battleTempData) {
            //初始化词条和数据
            let battleData = {
                "activeID": activeID,
                "stageData": {},
                "score": {},
                "time": {},
                "maxWordLevel": {},
                "id": this.uid
            }
            //初始化词条
            let maxWordLevel = battleData.maxWordLevel;
            let selectWord = [];
            let wordConfig = this.config("actEntrye");
            for (let i = 0; i < stageConfig.entryGroup.length; i++) {
                let wordID = stageConfig.entryGroup[i];
                let num = -1;
                if (wordConfig[wordID]) {
                    for (let j = 0; j < wordConfig[wordID].Coll.length; j++) {
                        if (wordConfig[wordID].Coll[j].defaultLock) {
                            num++;
                        }
                    }
                }
                maxWordLevel[wordID] = num;
                selectWord.push(0);
            }
            battleData.stageData[stageID] = {
                "selectWord": selectWord,
            }
            await battleCache.set(battleData.id, battleData);
            await battleCache.set(battleData.id, "beginTime", this.updater.time);
            return battleData.stageData[stageID];
        } else {
            battleTempData.stageData = JSON.parse(battleTempData.stageData);
            if (!battleTempData.stageData[stageID]) {
                //初始化词条
                let selectWord = [];
                for (let i = 0; i < stageConfig.entryGroup.length; i++) {
                    selectWord.push(-1);
                }
                battleTempData.stageData[stageID] = {
                    "selectWord": selectWord,
                }
                await battleCache.set(battleTempData.id, battleTempData);
                await battleCache.set(battleTempData.id, "beginTime", this.updater.time);
                return battleTempData.stageData[stageID];
            } else {
                //不是第一次打，直接开始
                await battleCache.set(battleTempData.id, "beginTime", this.updater.time);
                return battleTempData.stageData[stageID];
            }
        }
        // return ret;
    })

}

/**
 * @name endBattle
 * @param string activeID 活动ID
 * @param int stageID stageID
 * @param json data 通关数据
 * 结算战斗
 */
exports.endBattle = async function () {
    let activeID = this.get('activeID', 'string');
    let stageID = this.get('stageID', 'int');
    const battleData = this.get('data', 'json');
    //是否胜利
    let winFlag = 1;
    //是否开始了战斗
    //判断活动是否存在且在开启时间
    let query = {
    };
    query = {
        "_id": activeID,
    };
    let api = '/active/getAllByType',
        data = {
            "query": query,
            "keys": ["item", "s_key", "AType", "content", "name", "simg"],
        };
    return this.library('spirit/gzone', api, data).then(async ret => {
        if (!ret) {
            return;
        }
        let data = ret[0];
        let activeBeginTime = time.today(ret[0].STime);
        let todayBeginTime = time.today(this.updater.time);
        let circleDay = 7;
        //判断今天距离开启活动时间过去了多少天
        let subday = (todayBeginTime - activeBeginTime) / (24 * 60 * 60 * 1000) % circleDay;
        console.log("距离活动开启已经过去:" + subday + "天")
        let m = 10;
        let stageCompleteID = m * 1000 + subday + 1;
        //判断关卡ID是否匹配
        if (stageID != stageCompleteID) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        let stageConfig = this.config("actStage", stageID);
        if (!stageConfig) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        let battleCache = this.model.redis("weekBossCache", this.sid);
        //获取今日数据
        let battleTempData = await battleCache.get(this.uid);
        if (!battleTempData) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        if (!battleTempData.stageData) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        battleTempData.stageData = JSON.parse(battleTempData.stageData);
        battleTempData.maxWordLevel = JSON.parse(battleTempData.maxWordLevel);
        battleTempData.score = JSON.parse(battleTempData.score);
        battleTempData.time = JSON.parse(battleTempData.time);
        //不是第一次打，直接开始
        // battleTempData.stageData[stageID].beginTime = this.updater.time;
        // await battleCache.set(battleTempData.id, "beginTime", battleTempData.stageData[stageID].beginTime);
        //是否胜利
        if (!battleTempData.beginTime) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        battleTempData.beginTime = 0;
        let score = 0;
        if (battleData.win) {
            //每日首通奖励
            this.updater.daily.key("actBossReward");
            await this.updater.data();
            let actBossReward = this.updater.daily.get("actBossReward") || 0;
            if (!actBossReward) {
                //给奖励
                this.updater.daily.add("actBossReward", 1);
                this.updater.item.add(stageConfig.dailyReward, 1);
            }
            score = stageConfig.basic_Score;
            let wordConfig = this.config("actEntrye");
            //判断是否要更新词条
            for (let i = 0; i < stageConfig.entryGroup.length; i++) {
                if (battleTempData.stageData[stageID].selectWord[i] < 0) {
                    continue;
                }
                let wordID = stageConfig.entryGroup[i];
                if (battleTempData.maxWordLevel[wordID]) {
                    if (battleTempData.maxWordLevel[wordID] <= battleTempData.stageData[stageID].selectWord[i]) {
                        battleTempData.maxWordLevel[wordID]++;// = battleTempData.stageData[stageID].selectWord[i];
                        if (battleTempData.maxWordLevel[wordID] >= stageConfig.entryGroup.length) {
                            battleTempData.maxWordLevel[wordID] = stageConfig.entryGroup.length - 1;
                        }
                    }
                } else {
                    battleTempData.maxWordLevel[wordID] = battleTempData.stageData[stageID].selectWord[i];
                }
                score += wordConfig[wordID].Coll[battleTempData.stageData[stageID].selectWord[i]].entryScore;
            }
            // for (let i = 0; i < battleTempData.stageData[stageID].maxWordLevel.length; i++) {
            //     if (battleTempData.maxWordLevel[i] <= battleTempData.stageData[stageID].selectWord[i]) {
            //         //更新词条
            //         battleTempData.stageData[stageID].maxWordLevel[i]++;
            //     }
            //     let wordID = stageConfig.entryGroup[i];
            //     score += wordConfig[wordID].Coll[battleTempData.stageData[stageID].selectWord[i]].entryScore;
            // }
            //判断是否要更新最高积分
            if (battleTempData.score[stageConfig.missionGroupId]) {
                if (score > battleTempData.score[stageConfig.missionGroupId]) {
                    battleTempData.score[stageConfig.missionGroupId] = score;
                    this.updater.daily.set("65" + stageConfig.missionGroupId, score);
                }
            } else {
                battleTempData.score[stageConfig.missionGroupId] = score;
                this.updater.daily.set("65" + stageConfig.missionGroupId, score);
            }
            //判断是否要更新最快时间
            if (battleData.time) {
                if (battleTempData.time[stageConfig.missionGroupId]) {
                    if (battleData.time < battleTempData.time[stageConfig.missionGroupId]) {
                        battleTempData.time[stageConfig.missionGroupId] = battleData.time;
                        // this.updater.daily.set("65" + stageConfig.missionGroupId, score);
                    }
                } else {
                    battleTempData.time[stageConfig.missionGroupId] = battleData.time;
                    // this.updater.daily.set("65" + stageConfig.missionGroupId, score);
                }
            }

            // if (score > battleTempData.score[stageID].score) {
            //     battleTempData.score[stageID].score = score;
            //     this.updater.daily.set("65" + stageConfig.missionGroupId, score);
            // }
        }
        await battleCache.set(battleTempData.id, battleTempData);
        await battleCache.del(battleTempData.id, "beginTime");
        await this.updater.save();
        return battleTempData.stageData[stageID];
    })
}



/**
 * @name updateWord
 * @param string activeID 活动ID
 * @param string stageID 关卡ID
 * @param array wordData 词条信息
 * 更新词条
 */
exports.updateWord = async function () {
    let activeID = this.get('activeID', 'string');
    let wordData = this.get('wordData', 'array');
    let stageID = this.get('stageID', 'string');
    //判断活动是否存在且在开启时间
    let query = {
    };
    query = {
        "_id": activeID,
    };
    let api = '/active/getAllByType',
        data = {
            "query": query,
            "keys": ["item", "s_key", "AType", "content", "name", "simg"],
        };
    return this.library('spirit/gzone', api, data).then(async ret => {
        if (!ret) {
            return;
        }
        let data = ret[0];
        let activeBeginTime = time.today(ret[0].STime);
        let todayBeginTime = time.today(this.updater.time);
        let circleDay = 7;
        //判断今天距离开启活动时间过去了多少天
        let subday = (todayBeginTime - activeBeginTime) / (24 * 60 * 60 * 1000) % circleDay;
        console.log("距离活动开启已经过去:" + subday + "天")
        let m = 10;
        let stageCompleteID = m * 1000 + subday + 1;
        //判断关卡ID是否匹配
        if (stageID != stageCompleteID) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        let stageConfig = this.config("actStage", stageID);
        if (!stageConfig) {
            return this.quick_error("M7GHLB123", 'err request', stageID);
        }
        let battleCache = this.model.redis("weekBossCache", this.sid);
        //获取今日数据
        let battleTempData = await battleCache.get(this.uid);
        if (!battleTempData) {
            //初始化词条和数据
            let battleData = {
                "activeID": activeID,
                "stageData": {},
                "score": {},
                "time": {},
                "maxWordLevel": {},
                "id": this.uid
            }
            //初始化词条
            let maxWordLevel = battleData.maxWordLevel;
            let selectWord = [];
            let wordConfig = this.config("actEntrye");
            for (let i = 0; i < stageConfig.entryGroup.length; i++) {
                let wordID = stageConfig.entryGroup[i];
                let num = -1;
                if (wordConfig[wordID]) {
                    for (let j = 0; j < wordConfig[wordID].Coll.length; j++) {
                        if (wordConfig[wordID].Coll[j].defaultLock) {
                            num++;
                        }
                    }
                }
                maxWordLevel[wordID] = num;
                // if(){
                if (num >= wordData[i]) {
                    selectWord.push(wordData[i]);
                } else {
                    selectWord.push(num);
                }
                // }
                // selectWord.push(-1);
            }
            // battleData.stageData[stageID] = {
            //     "selectWord": selectWord,
            // }
            // await battleCache.set(battleData.id, battleData);
            // await battleCache.set(battleData.id, "beginTime", this.updater.time);
            // return battleData.stageData[stageID];
            // for (let i in maxWordLevel) {
            //     if (maxWordLevel[i] >= wordData[i]) {
            //         selectWord[i] = maxWordLevel[i];
            //     } else {
            //         selectWord[i] = wordData[i];
            //     }
            // }
            // for (let i = 0; i < maxWordLevel.length; i++) {
            // if (maxWordLevel[i] >= wordData[i]) {
            //     selectWord[i] = wordData[i];
            // } else {
            //     selectWord[i] = maxWordLevel[i];
            // }
            // }

            //
            battleData.stageData[stageID] = {
                "maxWordLevel": maxWordLevel,
                "selectWord": selectWord,
            }
            await battleCache.set(battleData.id, battleData);
            return selectWord;
        } else {
            battleTempData.stageData = JSON.parse(battleTempData.stageData);
            if (!battleTempData.stageData[stageID]) {
                //初始化词条
                let selectWord = [];
                for (let i = 0; i < stageConfig.entryGroup.length; i++) {
                    selectWord.push(-1);
                }
                battleTempData.stageData[stageID] = {
                    "selectWord": selectWord,
                }
                await battleCache.set(battleTempData.id, battleTempData);
                await battleCache.set(battleTempData.id, "beginTime", this.updater.time);
                return selectWord;// battleTempData.stageData[stageID].selectWord;
                // //初始化词条
                // let maxWordLevel = [];
                // let selectWord = [];
                // let wordConfig = this.config("actEntrye");
                // for (let i = 0; i < stageConfig.entryGroup.length; i++) {
                //     let wordID = stageConfig.entryGroup[i];
                //     let num = -1;
                //     if (wordConfig[wordID]) {
                //         for (let j = 0; j < wordConfig[wordID].Coll.length; j++) {
                //             if (wordConfig[wordID].Coll[j].defaultLock) {
                //                 num++;
                //             }
                //         }
                //     }
                //     maxWordLevel.push(num);
                //     selectWord.push(0);
                // }
                // for (let i = 0; i < maxWordLevel.length; i++) {
                //     if (maxWordLevel[i] >= wordData[i]) {
                //         selectWord[i] = wordData[i];
                //     } else {
                //         selectWord[i] = maxWordLevel[i];
                //     }
                // }
                // battleTempData.stageData[stageID] = {
                //     // "maxWordLevel": maxWordLevel,
                //     "selectWord": selectWord,
                // }
                // await battleCache.set(battleTempData.id, battleData);
                // return battleTempData.stageData[stageID].selectWord;
            } else {
                //更新词条
                battleTempData.maxWordLevel = JSON.parse(battleTempData.maxWordLevel);
                for (let i = 0; i < stageConfig.entryGroup.length; i++) {
                    let wordID = stageConfig.entryGroup[i];
                    if (battleTempData.maxWordLevel[wordID] == null) {
                        //去初始化这个词条
                        let wordConfig = this.config("actEntrye", wordID);
                        let num = -1;
                        if (wordConfig[wordID]) {
                            for (let j = 0; j < wordConfig[wordID].Coll.length; j++) {
                                if (wordConfig[wordID].Coll[j].defaultLock) {
                                    num++;
                                }
                            }
                        }
                        battleTempData.maxWordLevel[wordID] = num;
                    }
                    if (battleTempData.maxWordLevel[wordID] >= wordData[i]) {
                        if (wordData[i] == null) {
                            console.log("null 1 data:", i);
                        }
                        battleTempData.stageData[stageID].selectWord[i] = wordData[i];
                    } else {
                        if (wordData[i] == null) {
                            console.log("null 2 data:", i);
                        }
                        battleTempData.stageData[stageID].selectWord[i] = battleTempData.maxWordLevel[wordID];
                    }
                }
            }

            // for (let i = 0; i < battleTempData.stageData[stageID].maxWordLevel.length; i++) {
            //     if (battleTempData.stageData[stageID].maxWordLevel[i] >= wordData[i]) {
            //         battleTempData.stageData[stageID].selectWord[i] = wordData[i];
            //     } else {
            //         battleTempData.stageData[stageID].selectWord[i] = battleTempData.stageData[stageID].maxWordLevel[i];
            //     }
            // }
            // battleTempData.stageData[stageID].selectWord = wordData;
            await battleCache.set(battleTempData.id, battleTempData);
            return battleTempData.stageData[stageID].selectWord;
        }
    });
}

